package servlet;

import model.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "user_login", urlPatterns = "/user_login")
public class UserLoginServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端输入的用户名和密码
        String username = request.getParameter("login_username");
        String password = request.getParameter("login_password");

        // service方法处理登录
        User user = userService.login(username,password);

        // 数据库中存在该用户，可以登录
        if(user != null) {
            //登录成功，把用户信息存到session中，便于后续使用
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            //根据登录的用户类型跳转到不同的界面,管理员 or 普通用户
            if(user.isAdmin()){
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
            else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }
        // 数据库中不存在该用户名+密码的用户
        else {
            System.out.println("用户登录失败："+username);
            request.setAttribute("msg","用户名或密码错误！");
            request.getRequestDispatcher("/user_login.jsp").forward(request,response);
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
